package com.neusoft.domain;

import com.neusoft.exception.InsufficientFundsException;

import java.math.BigDecimal;

public class VirtualWallet {
    private final Long id;
    private final Long userId;
    private BigDecimal balance;
    private final BigDecimal creditLimit;         // 信用额度，默认 300
    private BigDecimal usedCredit;          // 已使用的信用额度
    private BigDecimal penaltyAmount;       // 滞纳金余额

    public VirtualWallet(Long id, Long userId, BigDecimal balance, BigDecimal creditLimit, BigDecimal usedCredit, BigDecimal penaltyAmount) {
        this.id = id;
        this.userId = userId != null ? userId : this.id;
        this.balance = balance != null ? balance : BigDecimal.ZERO;
        this.creditLimit = creditLimit != null ? creditLimit : BigDecimal.valueOf(300); // 默认信用额度为300
        this.usedCredit = usedCredit != null ? usedCredit : BigDecimal.ZERO;
        this.penaltyAmount = penaltyAmount != null ? penaltyAmount : BigDecimal.ZERO;
    }

    // 普通余额充值
    public void deposit(BigDecimal amount) {
        this.balance = this.balance.add(amount);
    }
    // 增加滞纳金
    public void addPenalty(BigDecimal amount) {
        this.penaltyAmount = this.penaltyAmount.add(amount);
    }

    // 支付滞纳金
    public void payPenalty(BigDecimal amount) throws InsufficientFundsException {
        if (this.penaltyAmount.compareTo(amount) < 0) {
            throw new InsufficientFundsException("滞纳金余额不足");
        }
        this.penaltyAmount = this.penaltyAmount.subtract(amount);
    }

    // 普通余额提现
    public void withdraw(BigDecimal amount) throws InsufficientFundsException {
        if (this.balance.compareTo(amount) < 0) {
            throw new InsufficientFundsException("余额不足");
        }
        this.balance = this.balance.subtract(amount);
    }

    // 使用信用额度消费
    public void useCredit(BigDecimal amount) throws InsufficientFundsException {
        if (availableCredit().compareTo(amount) < 0) {
            throw new InsufficientFundsException("信用额度不足");
        }
        this.usedCredit = this.usedCredit.add(amount);
    }

    // 还信用额度
    public void repayCredit(BigDecimal amount) {
        if (amount.compareTo(this.usedCredit) <= 0) {
            this.usedCredit = this.usedCredit.subtract(amount);
        } else {
            this.usedCredit = BigDecimal.ZERO;
        }
    }

    // 获取可用信用额度
    public BigDecimal availableCredit() {
        return this.creditLimit.subtract(this.usedCredit);
    }

    public BigDecimal getBalance() {
        return this.balance;
    }

    public BigDecimal getUsedCredit() {
        return this.usedCredit;
    }

    public void setBalance(BigDecimal subtract) {
        this.balance = subtract;
    }
}
